// router/app_router.dart

import 'package:fishing/models/booking_args.dart';
import 'package:fishing/providers/auth_provider.dart';
import 'package:fishing/views/fishing/fishing_book_page.dart';
import 'package:fishing/views/fishing/fishing_detail_page.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../providers/user_provider.dart';
import '../layouts/main_scaffold.dart';
import '../views/login/login_page.dart';
import '../views/home/home_page.dart';
import '../views/fishing/fishing_page.dart';
import '../views/community/community_page.dart';
import '../views/profile/profile_page.dart';
import '../views/profile/account_page.dart';
import '../views/circulate/circulate_page.dart';
import '../views/prebook/prebook_page.dart';
import '../views/refish/refish_page.dart';
import '../views/profile/help_center_page.dart';
import '../views/profile/my_favorites_page.dart';
import '../views/profile/my_reviews_page.dart';
import '../views/notifications/notifications_page.dart';
import '../views/news/news_page.dart';
import '../views/technique/technique_page.dart';
import '../views/technique/technique_detail_page.dart';
import '../views/community/community_create_page.dart';
import '../views/community/community_detail_page.dart';
import '../views/fishing_report/fishing_report_page.dart';
import '../views/fishing_king/fishing_king_page.dart';
import '../models/notice.dart';
import '../models/community_post.dart';

GoRouter createRouter(UserProvider userProvider, AuthProvider authProvider) {
  return GoRouter(
    initialLocation: '/login',
    refreshListenable: Listenable.merge([userProvider, authProvider]), // ✅ 同时监听
    redirect: (context, state) {
      // 等待认证初始化完成
      if (!authProvider.isInitialized) {
        return null; // 保持当前路由，等待初始化
      }
      
      final isAdmin = userProvider.isAdmin;
      final loggingIn = state.uri.toString() == '/login';
      final isLoggedIn = authProvider.isLoggedIn;
      
      debugPrint('路由重定向检查: isLoggedIn=$isLoggedIn, loggingIn=$loggingIn, currentPath=${state.uri.toString()}');
      
      // 如果未登录且不在登录页，跳转到登录页
      if (!isLoggedIn && !loggingIn) {
        debugPrint('未登录且不在登录页，跳转到登录页');
        return '/login';
      }
      
      // 如果已登录且在登录页，跳转到主页
      if (isLoggedIn && loggingIn) {
        final target = isAdmin ? '/refish' : '/home';
        debugPrint('已登录且在登录页，跳转到: $target');
        return target;
      }
      
      return null;
    },
    routes: [
      GoRoute(path: '/login', builder: (_, __) => const LoginPage()),
      ShellRoute(
        builder: (_, __, child) => MainScaffold(child: child),
        routes: [
          GoRoute(path: '/home', builder: (_, __) => const HomePage()),
          GoRoute(path: '/fishing', builder: (_, __) => const FishingPage()),
          GoRoute(
            path: '/fishing/:id',
            builder: (_, state) => FishingDetailPage(
              id: state.pathParameters['id']!,
            ),
            routes: [
              GoRoute(
                path: 'book/:id',
                builder: (context, state) {
                  final args = state.extra as BookingArgs?;
                  return FishingBooklPage(
                    id: state.pathParameters['id']!,
                    bookingArgs: args,
                  );
                },
              ),
            ],
          ),
          GoRoute(
            path: '/community',
            builder: (_, __) => const CommunityPage(),
            routes: [
              GoRoute(
                path: 'create',
                builder: (_, __) => const CommunityCreatePage(),
              ),
            ],
          ),
          GoRoute(
            path: '/profile',
            builder: (_, __) => const ProfilePage(),
            routes: [
              GoRoute(path: 'account', builder: (_, __) => const AccountPage()),
              GoRoute(path: 'help', builder: (_, __) => const HelpCenterPage()),
              GoRoute(path: 'favorites', builder: (_, __) => const MyFavoritesPage()),
              GoRoute(path: 'reviews', builder: (_, __) => const MyReviewsPage()),
            ],
          ),
          GoRoute(
              path: '/circulate', builder: (_, __) => const CirculatePage()),
          GoRoute(path: '/refish', builder: (_, __) => const RefishPage()),
        ],
      ),
      // 通知页面独立路由，不在 ShellRoute 内
      GoRoute(
          path: '/notifications',
          builder: (_, __) => const NotificationsPage()),
      // 资讯页面独立路由，不在 ShellRoute 内
      GoRoute(
        path: '/news',
        builder: (context, state) {
          final notice = state.extra as Notice?;
          if (notice == null) {
            // 如果没有传递notice，返回到首页
            return const Scaffold(
              body: Center(
                child: Text('通知不存在'),
              ),
            );
          }
          return NewsPage(notice: notice);
        },
      ),
      // 钓技学堂详情页面独立路由，不显示底部导航栏
      GoRoute(
        path: '/technique/:id',
        builder: (_, state) => TechniqueDetailPage(
          id: state.pathParameters['id']!,
        ),
      ),
      // 社区详情页面独立路由，不显示底部导航栏
      GoRoute(
        path: '/community/:id',
        builder: (context, state) {
          final post = state.extra as CommunityPost?;
          if (post == null) {
            return const Scaffold(
              body: Center(
                child: Text('帖子不存在'),
              ),
            );
          }
          return CommunityDetailPage(post: post);
        },
      ),
      // 我的预约页面（无底部导航栏）
      GoRoute(
        path: '/prebook',
        builder: (context, state) => const PrebookPage(),
      ),
      // 钓技学堂页面（无底部导航栏）
      GoRoute(
        path: '/technique',
        builder: (context, state) => const TechniquePage(),
      ),
      GoRoute(
        path: '/technique/:id',
        builder: (context, state) {
          final id = state.pathParameters['id']!;
          return TechniqueDetailPage(id: id);
        },
      ),
      // 钓况报告页面（无底部导航栏）
      GoRoute(
        path: '/fishing-report',
        builder: (context, state) => const FishingReportPage(),
      ),
      GoRoute(
        path: '/fishing-report/:id',
        builder: (context, state) {
          // ignore: unused_local_variable
          final id = state.pathParameters['id']!;
          return const FishingReportPage();
        },
      ),
      // 钓王榜页面（无底部导航栏）
      GoRoute(
        path: '/fishing-king',
        builder: (context, state) => const FishingKingPage(),
      ),
      // 其他功能页面（无底部导航栏）
      GoRoute(
        path: '/refish',
        builder: (context, state) => const RefishPage(),
      ),
      GoRoute(
        path: '/circulate',
        builder: (context, state) => const CirculatePage(),
      ),
    ],
  );
}
